
import 'package:dio/dio.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart' hide Response;
import 'apis.dart';
import 'dio_utils.dart';
import 'error_handle.dart';
import 'jb_storage_utils.dart';
import 'log_utils.dart';

// default token
const String defaultToken = '';
const String kRefreshTokenUrl = APIs.refreshToken;

String? getToken() {
  Map? userInfo = SpUtil.getObject("userInfo");
  return userInfo?['token'];
}

void setToken(accessToken) {
  JhStorageUtils.saveString('accessToken', accessToken);
}

String getRefreshToken() {
  var refreshToken = JhStorageUtils.getString('refreshToken') ?? '';
  return refreshToken;
}

void setRefreshToken(refreshToken) {
  JhStorageUtils.saveString('refreshToken', refreshToken);
}

// 统一添加 Header
class HeaderInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    options.headers['deviceId'] = 'deviceId';
    super.onRequest(options, handler);
  }
}

// 统一添加身份验证请求头（根据项目自行处理）
class AuthInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {

      final String? accessToken = getToken();
      if (accessToken != null) {
        print('token:accessToken');
        options.headers['x-session-token'] = '$accessToken';
      }

    super.onRequest(options, handler);
  }
}

/// 刷新Token（根据项目自行处理）
class TokenInterceptor extends QueuedInterceptor {

  @override
  Future<void> onResponse(Response<dynamic> response, ResponseInterceptorHandler handler) async {

    // List<String>? tokenList = response.headers['x-session-token'];
    // String? token = tokenList?.first;
    // if(token != null){
    //   UserData? user = UserInfoManager().userInfo;
    //   if(user != null){
    //     user.token = token;
    //     UserInfoManager().saveUserInfo(user);
    //   }
    // }
    //
    // // 401代表token过期
    // if (response.statusCode == ExceptionHandle.unauthorized ) {
    //   Fluttertoast.showToast(msg: "登录已过期");
    //   Get.toNamed(PageName.PAGE_LOGIN);
    //   print("realUri:${response.realUri}");
    // }
    super.onResponse(response, handler);
  }
}

/// 打印日志
class LoggingInterceptor extends Interceptor {
  late DateTime _startTime;
  late DateTime _endTime;

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    _startTime = DateTime.now();
    LogUtils.d('-------------------- Start --------URL:${options.path}------------');
    if (options.queryParameters.isEmpty) {
      LogUtils.d('RequestUrl: ${options.baseUrl}${options.path}');
    } else {
      LogUtils.d('RequestUrl: ${options.baseUrl}${options.path}?${Transformer.urlEncodeMap(options.queryParameters)}');
    }
    LogUtils.d('RequestMethod: ${options.method}');
    LogUtils.d('RequestHeaders:${options.headers}');
    LogUtils.d('RequestContentType: ${options.contentType}');
    LogUtils.d('RequestData: ${options.data.toString()}');
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response<dynamic> response, ResponseInterceptorHandler handler) {
    _endTime = DateTime.now();
    final int duration = _endTime.difference(_startTime).inMilliseconds;
    if (response.statusCode == ExceptionHandle.success) {
      LogUtils.d('ResponseCode: ${response.statusCode}');
    } else {
      LogUtils.e('ResponseCode: ${response.statusCode}');
    }
    // 输出结果
    LogUtils.d('返回数据：${response.data}');
    LogUtils.d('-------------------- End: $duration 毫秒 ---------URL:${response.requestOptions.path}-----------');
    super.onResponse(response, handler);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    LogUtils.d('-------------------- Error --------------------');
    super.onError(err, handler);
  }
}
